<template>
	<my-page title="资产详情" :is-back="true" :is-tabbar="false">
		<!-- 轮播图 -->
		<swiper class="swiper" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="500" indicator-active-color="#FFFFFF">
			<swiper-item v-for="(item, index) in imageList" :key="index">
				<image :src="getImageUrl(item)" mode="aspectFill" class="swiper-image" @click="previewImages(index)"></image>
			</swiper-item>
		</swiper>
		
		<!-- 资产标题和价格 -->
		<view class="asset-header">
			<view class="asset-title">{{assetInfo.name}}</view>
			<view class="tag_wrap">
				<view class="info-item">
					<view class="info-label">面积：{{assetInfo.area}}</view>
				</view>
				<view class="info-item">
					<view class="info-label">类型：{{getTypeName(assetInfo.type)}}</view>
				</view>
			</view>
			<view class="price-container">
					<view class="asset-price" v-if="shouldShowRentPrice">
						<text class="price-label">出租价格：</text>
						<text>{{assetInfo.rent}}</text>
					</view>
					<view class="asset-price transfer-price" v-if="shouldShowTransferPrice">
						<text class="price-label">出售价格：</text>
						<text>{{assetInfo.transferPrice}}</text>
					</view>
				</view>
				<view class="status-container" v-if="assetInfo.assetStatus !== undefined">
					<view class="asset-status">
						<text class="status-label">房屋状态：</text>
						<text class="status-value">{{getAssetStatusName(assetInfo.assetStatus)}}</text>
					</view>
				</view>
		</view>
		
		<!-- 资产基本信息 -->
		<view class="info-card">
		</view>
		
		<!-- 租赁信息 -->
		<view class="info-card">
			<view class="card-title">
				<text class="title-text">租赁信息</text>
			</view>
			<view class="info-item">
				<view class="info-label">所属单位：</view>
				<view class="info-value" :class="assetInfo.ownerUnit ? 'has-data' : 'no-data'">{{assetInfo.ownerUnit || '暂无'}}</view>
			</view>
			<view class="info-item">
				<view class="info-label">租赁期限：</view>
				<view class="info-value" :class="assetInfo.leaseTerm ? 'has-data' : 'no-data'">{{assetInfo.leaseTerm || '暂无'}}</view>
			</view>
			<view class="info-item">
				<view class="info-label">联系人：</view>
				<view class="info-value" :class="assetInfo.contactUnit ? 'has-data' : 'no-data'">{{assetInfo.contactUnit || '暂无'}}</view>
			</view>
			<view class="info-item">
				<view class="info-label">联系方式：</view>
				<view class="info-value" :class="assetInfo.contactInformation ? 'has-data' : 'no-data'">{{assetInfo.contactInformation || '暂无'}}</view>
			</view>
			<view class="info-item">
				<view class="info-label">详细地址：</view>
				<view class="info-value" :class="assetInfo.address ? 'has-data' : 'no-data'">{{assetInfo.address || '暂无'}}</view>
			</view>
			<view class="info-item">
				<view class="info-label">{{getBuildingInfoLabel(assetInfo) || '位置信息'}}：</view>
				<view class="info-value" :class="getBuildingInfo(assetInfo) ? 'has-data' : 'no-data'">{{getBuildingInfo(assetInfo) || '暂无'}}</view>
			</view>
			<view class="info-item">
				<view class="info-label">所在楼层：</view>
				<view class="info-value" :class="assetInfo.floor ? 'has-data' : 'no-data'">{{assetInfo.floor || '暂无'}}</view>
			</view>
			<view class="info-item">
				<view class="info-label">层高：</view>
				<view class="info-value" :class="assetInfo.floorHeight ? 'has-data' : 'no-data'">{{assetInfo.floorHeight || '暂无'}}</view>
			</view>
			<view class="info-item">
				<view class="info-label">用途类型：</view>
				<view class="info-value" :class="assetInfo.usageType ? 'has-data' : 'no-data'">{{assetInfo.usageType || '暂无'}}</view>
			</view>
			<view class="info-item">
				<view class="info-label">盘活方式：</view>
				<view class="info-value" :class="assetInfo.revitalizationMethod ? 'has-data' : 'no-data'">{{assetInfo.revitalizationMethod || '暂无'}}</view>
			</view>
			<view class="info-item">
				<view class="info-label">权利性质：</view>
				<view class="info-value" :class="assetInfo.pricePropertyNature ? 'has-data' : 'no-data'">{{assetInfo.pricePropertyNature || '暂无'}}</view>
			</view>
			<view class="info-item">
				<view class="info-label">评估时间：</view>
				<view class="info-value" :class="assetInfo.evaluationTime ? 'has-data' : 'no-data'">{{assetInfo.evaluationTime || '暂无'}}</view>
			</view>
			<view class="info-item">
				<view class="info-label">土地性质：</view>
				<view class="info-value" :class="assetInfo.landNature ? 'has-data' : 'no-data'">{{assetInfo.landNature || '暂无'}}</view>
			</view>
			<view class="info-item">
				<view class="info-label">装修：</view>
				<view class="info-value" :class="assetInfo.decoration ? 'has-data' : 'no-data'">{{assetInfo.decoration || '暂无'}}</view>
			</view>
			<view class="info-item">
				<view class="info-label">建筑年代：</view>
				<view class="info-value" :class="assetInfo.buildingAge ? 'has-data' : 'no-data'">{{assetInfo.buildingAge || '暂无'}}</view>
			</view>
		</view>
		
		<!-- 详情介绍 -->
		<view class="info-card info-card-last" v-if="assetInfo.remark">
			<view class="card-title">
				<text class="title-text">详情介绍</text>
			</view>
			<view class="remark-content">
				{{assetInfo.remark}}
			</view>
		</view>
		
		<!-- 底部安全区域占位，确保内容不被底部操作栏遮挡 -->
		<view class="safe-area-placeholder"></view>
		
		<!-- 底部操作栏 -->
		<view class="action-bar">
			<view class="action-btn collect" @click="toggleCollect">
				<text class="iconfont" :class="isCollected ? 'icon-stared' : 'icon-star'"></text>
				<text>{{isCollected ? '已收藏' : '收藏'}}</text>
			</view>
			<view class="action-btn nav" @click="handleNavigation">
				<text class="iconfont icon-navigate"></text>
				<text>一键导航</text>
			</view>
			<view class="action-btn contact" @click="handleContact">
				<text>一键联系</text>
			</view>
			<!-- 底部安全区域 -->
			<view class="safe-area-bottom"></view>
		</view>
	</my-page>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { ref, onMounted, computed } from 'vue'
import { getAssetDetail } from '@/api/assets'
import { getDictData } from '@/api/system'
import { checkIsCollected, addCollection, cancelCollection } from '@/api/collection'
import MyPage from '@/components/MyPage.vue'
import suoluetuPic from '@/static/images/suoluetu.png'
import { useStore } from 'vuex'
const store = useStore()
// 用户ID，实际项目中应该从登录信息中获取
const userId = computed(() => {
	return store.state.user.user.userId
}) // 假设当前用户ID为1

// 资产类型字典
const typeDict = ref([])

// 资产状态字典
const assetStatusDict = ref([])

// 资产ID
const assetId = ref(null)

// 资产详情
const assetInfo = ref({})

// 图片列表
const imageList = ref([])

// 是否已收藏
const isCollected = ref(false)

// 根据盘活方式判断是否显示出租价格
const shouldShowRentPrice = computed(() => {
	const method = assetInfo.value.revitalizationMethod
	const hasRentPrice = assetInfo.value.rent
	
	if (!hasRentPrice) return false
	
	return method === '出租' || method === '租售均可' || method === '先租后让'
})

// 根据盘活方式判断是否显示出售价格
const shouldShowTransferPrice = computed(() => {
	const method = assetInfo.value.revitalizationMethod
	const hasTransferPrice = assetInfo.value.transferPrice
	
	if (!hasTransferPrice) return false
	
	return method === '出售' || method === '租售均可' || method === '先租后让'
})

// 记录浏览历史
const recordHistory = (assetData) => {
	try {
		// 读取已有历史
		let history = uni.getStorageSync('assetViewHistory') || '[]'
		let historyList = JSON.parse(history)
		
		// 当前日期（仅日期，不含时间）
		const today = new Date()
		const dateStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`
		
		// 构建历史记录项
		const historyItem = {
			id: assetData.id,
			name: assetData.name,
			imageUrl: assetData.imageUrl,
			area: assetData.area,
			rent: assetData.rent,
			type: assetData.type,
			address: assetData.address,
			date: dateStr,
			timestamp: new Date().getTime() // 用于排序
		}
		
		// 移除已有的相同资产记录
		historyList = historyList.filter(item => item.id !== historyItem.id)
		
		// 添加到列表开头
		historyList.unshift(historyItem)
		
		// 限制最多50条记录
		if (historyList.length > 50) {
			historyList = historyList.slice(0, 50)
		}
		
		// 保存到本地存储
		uni.setStorageSync('assetViewHistory', JSON.stringify(historyList))
	} catch (e) {
		console.error('记录浏览历史失败', e)
	}
}

// 记录联系历史
const recordContactHistory = (assetData, phone) => {
	try {
		// 读取已有历史
		let history = uni.getStorageSync('assetContactHistory') || '[]'
		let historyList = JSON.parse(history)
		
		// 当前日期（仅日期，不含时间）
		const today = new Date()
		const dateStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`
		const timeStr = `${String(today.getHours()).padStart(2, '0')}:${String(today.getMinutes()).padStart(2, '0')}`
		
		// 构建历史记录项
		const historyItem = {
			id: assetData.id,
			name: assetData.name,
			imageUrl: assetData.imageUrl,
			phone: phone,
			date: dateStr,
			time: timeStr,
			timestamp: new Date().getTime() // 用于排序
		}
		
		// 添加到列表开头
		historyList.unshift(historyItem)
		
		// 限制最多50条记录
		if (historyList.length > 50) {
			historyList = historyList.slice(0, 50)
		}
		
		// 保存到本地存储
		uni.setStorageSync('assetContactHistory', JSON.stringify(historyList))
	} catch (e) {
		console.error('记录联系历史失败', e)
	}
}

// 获取资产详情
const getAssetInfo = async (id) => {
	try {
		uni.showLoading({
			title: '加载中...'
		})
		
		const res = await getAssetDetail(id)
		
		if (res.code === 200 && res.data) {
			assetInfo.value = res.data
			
			// 处理图片列表
			if (res.data.imageUrl) {
				imageList.value = res.data.imageUrl.split(',')
			} else {
				imageList.value = [suoluetuPic]
			}
			
			// 记录浏览历史
			recordHistory(res.data)
			
			// 检查是否已收藏
			checkCollection()
		} else {
			uni.showToast({
				title: res.msg || '加载失败',
				icon: 'none'
			})
		}
		
		uni.hideLoading()
	} catch (error) {
		console.error('获取资产详情失败', error)
		uni.hideLoading()
		uni.showToast({
			title: '网络异常，请稍后再试',
			icon: 'none'
		})
	}
}

// 处理图片URL
const getImageUrl = (imageUrl) => {
	if (!imageUrl) return '/static/images/suoluetu.png'
	
	// 检查是否已包含http
	if (imageUrl.startsWith('http')) {
		return imageUrl
	}
	
	// 拼接基础URL
	return import.meta.env.VITE_APP_BASE_API + imageUrl
}

// 预览图片
const previewImages = (index) => {
	const urls = imageList.value.map(img => getImageUrl(img))
	uni.previewImage({
		urls: urls,
		current: index
	})
}

// 获取资产类型名称
const getTypeName = (type) => {
	if (typeDict.value && typeDict.value.length > 0) {
		const typeItem = typeDict.value.find(item => item.value == type)
		if (typeItem) return typeItem.label
	}
	
	// 默认类型映射
	const typeMap = {
		0: '商铺',
		1: '住宅',
		2: '办公室',
		3: '厂房',
		4: '仓库'
	}
	
	return typeMap[type] || '其他'
}

// 获取资产状态名称
const getAssetStatusName = (status) => {
	if (assetStatusDict.value && assetStatusDict.value.length > 0) {
		const statusItem = assetStatusDict.value.find(item => item.value == status)
		if (statusItem) return statusItem.label
	}
	
	// 默认状态映射
	const statusMap = {
		0: '维护中',
		1: '展示中',
		2: '已出租'
	}
	
	return statusMap[status] || '未知状态'
}

// 获取楼栋/单元/房号格式化显示
const getBuildingInfo = (assetData) => {
	const parts = []
	
	// 处理楼栋
	if (assetData.building && assetData.building.trim()) {
		parts.push(assetData.building.trim())
	}
	
	// 处理单元
	if (assetData.unit && assetData.unit.trim()) {
		parts.push(assetData.unit.trim())
	}
	
	// 处理房号
	if (assetData.roomNumber && assetData.roomNumber.trim()) {
		parts.push(assetData.roomNumber.trim())
	}
	
	return parts.length > 0 ? parts.join('/') : ''
}

// 获取楼栋/单元/房号标签名称
const getBuildingInfoLabel = (assetData) => {
	const hasBuilding = assetData.building && assetData.building.trim()
	const hasUnit = assetData.unit && assetData.unit.trim()
	const hasRoomNumber = assetData.roomNumber && assetData.roomNumber.trim()
	
	if (hasBuilding && hasUnit && hasRoomNumber) {
		return "楼栋/单元/房号"
	} else if (hasBuilding && hasUnit) {
		return "楼栋/单元"
	} else if (hasBuilding && hasRoomNumber) {
		return "楼栋/房号"
	} else if (hasUnit && hasRoomNumber) {
		return "单元/房号"
	} else if (hasBuilding) {
		return "楼栋"
	} else if (hasUnit) {
		return "单元"
	} else if (hasRoomNumber) {
		return "房号"
	} else {
		return ""
	}
}

// 格式化日期
const formatDate = (dateStr) => {
	if (!dateStr) return ''
	const date = new Date(dateStr)
	if (isNaN(date.getTime())) return ''
	
	const year = date.getFullYear()
	const month = String(date.getMonth() + 1).padStart(2, '0')
	const day = String(date.getDate()).padStart(2, '0')
	
	return `${year}-${month}-${day}`
}

// 初始化字典数据
const initDictData = async () => {
	try {
		// 获取资产类型字典
		const assetTypeRes = await getDictData('asset_type')
		if (assetTypeRes.code === 200 && assetTypeRes.data) {
			typeDict.value = assetTypeRes.data.map(item => ({
				label: item.dictLabel,
				value: item.dictValue
			}))
		}
		
		// 获取资产状态字典
		const assetStatusRes = await getDictData('asset_status')
		if (assetStatusRes.code === 200 && assetStatusRes.data) {
			assetStatusDict.value = assetStatusRes.data.map(item => ({
				label: item.dictLabel,
				value: item.dictValue
			}))
		}
	} catch (error) {
		console.error('加载字典数据失败', error)
	}
}

// 检查是否已收藏
const checkCollection = async () => {
	try {
		const res = await checkIsCollected(userId.value, assetId.value)
		if (res.code === 200) {
			isCollected.value = res.data
		}
	} catch (error) {
		console.error('检查收藏状态失败', error)
	}
}

// 切换收藏状态
const toggleCollect = async () => {
	try {
		uni.showLoading({
			title: isCollected.value ? '取消收藏中...' : '收藏中...'
		})
		
		let res
		if (isCollected.value) {
			// 取消收藏
			res = await cancelCollection(userId.value, assetId.value)
		} else {
			// 添加收藏
			res = await addCollection(userId.value, assetId.value)
		}
		
		if (res.code === 200) {
			isCollected.value = !isCollected.value
			uni.showToast({
				title: isCollected.value ? '已收藏' : '已取消收藏',
				icon: 'success'
			})
		} else {
			uni.showToast({
				title: res.msg || '操作失败',
				icon: 'none'
			})
		}
		
		uni.hideLoading()
	} catch (error) {
		console.error('操作收藏失败', error)
		uni.hideLoading()
		uni.showToast({
			title: error,
			icon: 'none'
		})
	}
}

// 处理导航
const handleNavigation = () => {
	if (!assetInfo.value.address) {
		uni.showToast({
			title: '暂无地址信息',
			icon: 'none'
		})
		return
	}
	
	uni.openLocation({
	    latitude: parseFloat(assetInfo.value.latitude),
	    longitude: parseFloat(assetInfo.value.longitude),
		name: assetInfo.value.name,
		address: assetInfo.value.address,
		fail: () => {
			uni.showToast({
				title: '打开地图失败',
				icon: 'none'
			})
		}
	})
}

// 处理联系
const handleContact = () => {
	if (!assetInfo.value.contactInformation) {
		uni.showToast({
			title: '暂无联系方式',
			icon: 'none'
		})
		return
	}
	
	// 记录联系历史
	recordContactHistory(assetInfo.value, assetInfo.value.contactInformation)
	
	uni.makePhoneCall({
		phoneNumber: assetInfo.value.contactInformation,
		fail: () => {
			uni.showToast({
				title: '拨打电话失败',
				icon: 'none'
			})
		}
	})
}

// 页面加载
onLoad((options) => {
	if (options.id) {
		assetId.value = options.id
		getAssetInfo(options.id)
	} else {
		uni.showToast({
			title: '参数错误',
			icon: 'none'
		})
	}
})

// 页面初始化
onMounted(() => {
	initDictData()
})
</script>

<style lang="scss" scoped>
@import '@/static/styles/index.scss';

.swiper {
	width: 100%;
	height: 500rpx;
	
	.swiper-image {
		width: 100%;
		height: 100%;
	}
}

.asset-header {
	margin: -60rpx 30rpx;
	padding: 30rpx;
	background-color: #fff;
	position: relative;
	z-index: 1;
	border-radius: 14rpx;
	.asset-title {
		font-size: 36rpx;
		font-weight: bold;
		color: rgba(0, 36, 87, 1);
		margin-bottom: 20rpx;
	}
	
	
	.tag_wrap {
		display: flex;
		align-items: center;
		.info-item {
			margin-right: 15rpx;
			background: #c4d7fd;
			color: rgba(4, 94, 240, 1);
			font-size: 24rpx;
			padding: 6rpx 10rpx;
			border-radius: 6rpx;
		}
		.info-item:nth-child(2) {
			background: #d9f5f3;
			color: rgba(0, 186, 173, 1);
		}
		
	}
	.price-container {
			display: flex;
			justify-content: space-between;
			margin-top: 20rpx;
			width: 100%;
		}
		.asset-price {
			font-size: 32rpx;
			color: #ff5a5f;
			font-weight: bold;
			margin-bottom: 10rpx;
			
			.price-label {
				font-size: 24rpx;
				font-weight: normal;
				color: #666;
				margin-right: 10rpx;
			}
		}
		.transfer-price {
			color: #ff9500;
		}
		.status-container {
			margin-top: 20rpx;
			.asset-status {
				font-size: 28rpx;
				color: #666;
				.status-label {
					font-weight: bold;
					margin-right: 10rpx;
				}
				.status-value {
					color: rgba(0, 36, 87, 1);
				}
			}
		}
}

.info-card {
	margin: 20rpx 30rpx;
	padding: 30rpx;
	background-color: #fff;
	border-radius: 12rpx;
	
	&.info-card-last {
		margin-bottom: 140rpx; /* 为底部操作栏和安全区域留出足够空间 */
	}
	
	.card-title {
		margin-bottom: 20rpx;
		padding-bottom: 20rpx;
		border-bottom: 1px solid #f5f5f5;
		
		.title-text {
			font-size: 32rpx;
			font-weight: bold;
			color: rgba(0, 36, 87, 1);
			position: relative;
			padding-left: 20rpx;
			
			&::before {
				content: '';
				position: absolute;
				left: 0;
				top: 50%;
				transform: translateY(-50%);
				width: 6rpx;
				height: 30rpx;
				background-color: #2979ff;
				border-radius: 3rpx;
			}
		}
	}
	
	.info-item {
		display: flex;
		margin-bottom: 20rpx;
		
		.info-label {
			width: 180rpx;
			color: #999;
			font-size: 28rpx;
		}
		
		.info-value {
			flex: 1;
			font-size: 28rpx;
			
			&.has-data {
				color: rgba(0, 36, 87, 1); // 有数据时深灰色（深蓝灰）
			}
			
			&.no-data {
				color: #ccc; // 无数据时浅灰色
			}
		}
	}
	
	.remark-content {
		font-size: 28rpx;
		color: #666;
		line-height: 1.6;
	}
}

.safe-area-placeholder {
	height: 120rpx; /* 为底部操作栏预留空间 */
	width: 100%;
}

.action-bar {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: #fff;
	display: flex;
	align-items: center;
	box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.05);
	z-index: 99;
	padding-bottom: constant(safe-area-inset-bottom); /* iOS 11.0 */
	padding-bottom: env(safe-area-inset-bottom); /* iOS 11.2+ */
	padding-right: 20rpx;
	.action-btn {
		height: 100rpx;
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;
		color: #666;
		
		.iconfont {
			font-size: 50rpx;
		}
		
		&.collect {
			flex: 0.5;
			.icon-stared {
				color: #ff9800;
			}
		}
		
		&.nav {
			height: 80rpx;
			border-radius: 234px;
			background: linear-gradient(270deg, rgba(0, 186, 173, 1) 0%, rgba(67, 207, 124, 1) 99.65%);
			color: #fff;
		}
		
		&.contact {
			margin-left: 20rpx;
			height: 80rpx;
			border-radius: 234px;
			background: linear-gradient(270deg, rgba(0, 111, 255, 1) 0%, rgba(11, 69, 217, 1) 99.65%);
			color: #fff
		}
	}
	
	.safe-area-bottom {
		height: constant(safe-area-inset-bottom); /* iOS 11.0 */
		height: env(safe-area-inset-bottom); /* iOS 11.2+ */
		width: 100%;
		background-color: #fff;
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: -1;
	}
}
</style> 